package com.budong.api;

import com.budong.common.ApiResponse;
import com.budong.service.GifService;
import com.budong.utils.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static com.budong.common.GifConstant.GIF_MAKE_ERROR;
import static com.budong.common.GifConstant.UNITE_GIF_ERROR;

/**
 * Created by jianweilin on 2017/1/14.
 */
@RestController
@RequestMapping(value = "/v1",produces = "application/json")
public class GifController {

    @Autowired
    private GifService gifService;

    @RequestMapping(value = "/video/real/url",method = RequestMethod.POST)
    public ApiResponse<List<String>> realUrl(@RequestParam String videoUrl){
        if(!StringUtils.isSupport(videoUrl)){
            return ApiResponse.failed("目前只支持 优酷、土豆、腾讯视频git、AcFun弹幕网、爆米花网、风行网、音悦Tai的解析!");
        }

        List<String> realUrls = gifService.getRealUrl(videoUrl);

        if(realUrls.size() == 0) {
            return ApiResponse.failed("解析播放地址失败,请重试!");
        }

        if(!StringUtils.isMP4URL(realUrls)){
            return ApiResponse.failed("解析播放成功,但没有MP4播放格式视频!");
        }

        return ApiResponse.success(realUrls);
    }


    @RequestMapping(value = "/single/video/gif",method = RequestMethod.POST)
    public ApiResponse<String> singVideoGif(@RequestParam String realUrl,@RequestParam String startTime,@RequestParam String endTime,@RequestParam String gifSize){
        if(!StringUtils.isTimeFormat(Arrays.asList(startTime,endTime))){
            return ApiResponse.failed("时间格式有误,请重新输入");
        }
        return ApiResponse.success(gifService.getSingVideoGif(realUrl,startTime,endTime,gifSize));
    }

    @RequestMapping(value = "/mutil/video/gif",method = RequestMethod.POST)
    public ApiResponse<String> mutilVideoGif(@RequestParam String realUrlA,@RequestParam String startTimeA,@RequestParam String endTimeA,@RequestParam String realUrlB,@RequestParam String startTimeB,@RequestParam String endTimeB,@RequestParam String gifSize){

        if(!StringUtils.isTimeFormat(Arrays.asList(startTimeA,endTimeA,startTimeB,endTimeB))){
            return ApiResponse.failed("时间格式有误,请重新输入");
        }

        String qiNiuGif = gifService.getMutilVideoGif(realUrlA,startTimeA,endTimeA,realUrlB,startTimeB,endTimeB,gifSize);
        if(GIF_MAKE_ERROR.equals(qiNiuGif)){
            return ApiResponse.failed("生成GIF失败,请重试!");
        }

        if(UNITE_GIF_ERROR.equals(qiNiuGif)){
            return ApiResponse.failed("录制GIF跨视频源,合并GIF失败!");
        }
        return ApiResponse.success(qiNiuGif);
    }

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public ResponseEntity<InputStreamResource> downloadFile(@RequestParam String gifUrl) throws IOException {
        InputStream inputStream = new URL(gifUrl).openStream();
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\".gif", UUID.randomUUID().toString()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");

        return ResponseEntity
                .ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(inputStream));
    }


    @RequestMapping(value = "/batch/download",method = RequestMethod.POST,produces="application/zip")
    public void batchDownload(@RequestParam String gifUrls,HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.addHeader("Content-Disposition",String.format("attachment; filename=\"%s\".zip", UUID.randomUUID().toString()));
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "GET, POST, HEAD, PUT, DELETE");
        response.addHeader("Access-Control-Max-Age", "36000");

        ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());
        List<String> gifs = Arrays.asList(gifUrls.split(","));
        System.out.println("gifs => " + gifs.size());
        if(gifs.size() == 0){
            return;
        }

        for(String gif : gifs){
            zipOutputStream.putNextEntry(new ZipEntry(UUID.randomUUID().toString().concat(".gif")));
            InputStream inputStream = new URL(gif).openStream();
            IOUtils.copy(inputStream, zipOutputStream);
            inputStream.close();
            zipOutputStream.closeEntry();
        }
        zipOutputStream.close();
    }



}
